package com.server.chart;

import com.dao.chart.ChartsConfigMapper;
import com.dao.chart.ShowChartsMapper;
import com.model.bo.*;
import com.model.pojo.RepCode;
import com.model.pojo.RepEntity;
import com.model.vo.configVo.PieConfigInfo;
import com.model.vo.dataVo.ChartsDataInfo;
import com.config.BasesSource.DynamicDataSourceContextHolder;
import com.util.CalculationJudgeUtil;
import com.util.ScreenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class ShowPieService {
    @Autowired
    ShowChartsMapper showChartsMapper;
    @Autowired
    TimeConverterUtil timeConverterUtil;
    @Autowired
    CalculationJudgeUtil calculationJudgeUtil;
    @Autowired
    ChartsConfigMapper chartsConfigMapper;
    @Autowired
    ScreenUtil screenUtil;
    @Autowired
    GetChartsDataUtilService getChartsDataUtilService;
    @Autowired
    ChartsUtilService chartsUtilService;

    /*
    Pie数据展示
     */
    public RepEntity showPie(PieConfigInfo pieConfigInfo, String token, int dashId){
        ChartsDataInfo<PieSeries> chartsDataInfo = new ChartsDataInfo();
        TimeReture timeReture = new TimeReture();
        if (pieConfigInfo == null || "".equals(pieConfigInfo)){
            return new RepEntity(RepCode.Null);
        }
        int id = pieConfigInfo.getId();
        //获取列配置
        ChartsColumnConfig chartsColumn = chartsConfigMapper.getChartsColumn(id);
        if (chartsColumn == null || "".equals(chartsColumn)){
            return new RepEntity(RepCode.Null);
        }
        chartsDataInfo.setChartsColumnConfig(chartsColumn);
        String tableName = chartsUtilService.getSqlStr(token, id, dashId);
        if ("".equals(tableName)){
            return new RepEntity(RepCode.NoAuthority);
        }

        int baseId = getChartsDataUtilService.getBaseId(id);
        System.out.println("切换数据库"+String.valueOf(baseId));
        try{
            if (!DynamicDataSourceContextHolder.isContainsDataSource(String.valueOf(baseId))) {
                //joinPoint.getSignature() ：获取连接点的方法签名对象
                System.out.println("数据源 " + String.valueOf(baseId) + " 不存在使用默认的数据源 -> ");
                return new RepEntity(RepCode.DataSourceNull);
            } else {
                System.out.println("使用数据源：" + String.valueOf(baseId));
                DynamicDataSourceContextHolder.setDataSourceType(String.valueOf(baseId));
            }

        String xColumn = pieConfigInfo.getLegendData().getColumnRename();
        String yColumn = pieConfigInfo.getSeries().getColumnRename();
        String xColumnType = pieConfigInfo.getLegendData().getColumnType();

        String xAxisType = pieConfigInfo.getLegendData().getShowDataType();

        if (xColumn == null || "".equals(xColumn) || yColumn == null || "".equals(yColumn)){
            return new RepEntity(RepCode.nullAxis);
        }

        String yType = pieConfigInfo.getSeries().getShowDataType();
        String yAxisType = calculationJudgeUtil.Judge(yType);


        PieSeries series = new PieSeries();
        List<PieSeriesMap> value = new ArrayList<PieSeriesMap>();
        List<PieSeries> serieses = new ArrayList<PieSeries>();    //生成柱状图的系列
        List<String> xAxisData = new ArrayList<String>();  //X轴自己用
        List<String> xData = new ArrayList<String>();      //X轴前端用

            //取筛选列表
            List<Screen> screens = pieConfigInfo.getFilters();
            ScreenStr scr = new ScreenStr();
            String screen = "";               //正常筛选条件
            String screenToColumn = "";       //跟目标列相同的筛选条件
            String screenToColumnS = "";       //跟目标列相同的筛选条件
            if ("".equals(screens) || screens == null || screens.size() == 0){
                screen = "";
            }else {
                scr = screenUtil.screensUtil(screens, xColumn, xColumnType);
                screen = scr.getRet();
                screenToColumn = scr.getWithColumnRet();
                StringBuilder sb = new StringBuilder(screenToColumn);
                System.out.println("sb:"+sb);
                if (screenToColumn != null && !("".equals(screenToColumn))){
                    screenToColumnS = screenToColumn + " " + screen;               //and
                    screenToColumn = String.valueOf(sb .replace(1, 5, "where "));
                    screen = screenToColumn + " " + screen;         //where
                    System.out.println("screen:" + screen);
                } else {
                    StringBuilder sb1 = new StringBuilder(screen);
                    screenToColumnS = screen;
                    screen = String.valueOf(sb1 .replace(1, 5, "where "));
                }
            }

        //X轴
        //判断是否为日期类型
        if ("time".equals(xColumnType)){
            timeReture = timeConverterUtil.timeConverter(xColumn, tableName, xAxisType, screen, 20);
            xAxisData = timeReture.getValues();
            chartsDataInfo.setTooMany(timeReture.isOverdose());
            xData = timeConverterUtil.toRespons(xAxisData,xAxisType );
            System.out.println("data:"+xAxisData);
        }else {
            int count = showChartsMapper.getNumForX(xColumn, tableName);
            if (count > 20){
                chartsDataInfo.setTooMany(true);
            }
            xAxisData = showChartsMapper.getXAxis(xColumn, tableName, screen, 20);

        }
        if ("".equals(xAxisData) || xAxisData == null || xAxisData.size() == 0){
            return new RepEntity(RepCode.Null);
        }
        if ("week".equals(xAxisType) || "month".equals(xAxisType) || "quarter".equals(xAxisType)){
            chartsDataInfo.setxAxis(xData);
        }else {
            chartsDataInfo.setxAxis(xAxisData);
        }

        //无分组时Y值
        Iterator itX = xAxisData.iterator();
        while (itX.hasNext()){
            String xdata = (String)itX.next();
            if ("".equals(xdata) || xdata == null){
                continue;
            }
            double valueOne = 0;
            String valueOnes = null;
            PieSeriesMap pieSeriesMap = new PieSeriesMap();
            if ("time".equals(xColumnType)){
                valueOnes = timeConverterUtil.getTimeValueConverter(yColumn, xColumn, tableName, yAxisType, xAxisType, xdata, screenToColumnS);
            }else {
                if (xdata == null || "".equals(xdata)){
                    valueOnes = showChartsMapper.getValuesIsNull(yColumn, xColumn, tableName, yAxisType, screenToColumnS);
                }else {
                    valueOnes = showChartsMapper.getValues(yColumn, xColumn, tableName, yAxisType, xdata, screenToColumnS);
                }
            }
            if (valueOnes == null || "".equals(valueOnes)){
                valueOne = 0;
            }else {
                valueOne = Double.parseDouble(valueOnes);
            }
            pieSeriesMap.setName(xdata);
            pieSeriesMap.setValue(valueOne);
            value.add(pieSeriesMap);
        }

        series.setName(pieConfigInfo.getSeries().getColumnName());
        series.setValue(value);
        serieses.add(series);

        chartsDataInfo.setSerieses(serieses);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("异常");
            return new RepEntity(RepCode.erro);
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }

        return new RepEntity(RepCode.success, chartsDataInfo);
    }


}
